package com.webank.wedatasphere.qualitis.handler;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.webank.wedatasphere.qualitis.project.dao.repository.ProjectMuLuRepository;
import com.webank.wedatasphere.qualitis.project.dao.repository.ProjectRepository;
import com.webank.wedatasphere.qualitis.project.entity.Project;
import com.webank.wedatasphere.qualitis.project.entity.ProjectMuLu;
import com.webank.wedatasphere.qualitis.response.BiaoZunExcelDTO;
import com.webank.wedatasphere.qualitis.util.LocalTimeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class ExcelBiaoZunListener extends AnalysisEventListener<BiaoZunExcelDTO> {

   private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;


    /**
     * 缓存的数据
     */
    private List<BiaoZunExcelDTO> cachedDataList = new ArrayList<>(BATCH_COUNT);
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private ProjectRepository projectRepository;

    private ProjectMuLuRepository projectMuLuRepository;

    private List<ProjectMuLu> muLuRepositoryAll;

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param projectRepository
     */
    public ExcelBiaoZunListener(ProjectRepository projectRepository,ProjectMuLuRepository projectMuLuRepository) {
        this.projectRepository = projectRepository;
        this.projectMuLuRepository = projectMuLuRepository;
        this.muLuRepositoryAll = this.projectMuLuRepository.findAll();
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#()}
     * @param context
     */
    @Override
    public void invoke(BiaoZunExcelDTO data, AnalysisContext context) {
        logger.info("解析到一条数据:{}", JSON.toJSONString(data));
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = new ArrayList<>(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        logger.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        logger.info("{}条数据，开始存储数据库！", cachedDataList.size());
        for (BiaoZunExcelDTO biaoZunExcelDTO : cachedDataList) {
            if (StringUtils.isBlank(biaoZunExcelDTO.getCnName())){
                continue;
            }
            for (ProjectMuLu muLu : muLuRepositoryAll) {
                if (muLu.getTitle().equals(biaoZunExcelDTO.getSjzlbzml())) {
                    biaoZunExcelDTO.setSjzlbzml(muLu.getId().toString());
                    break;
                }
            }
            // 处理数据
            Project project = new Project();
            project.setCnName(biaoZunExcelDTO.getCnName());
            project.setFbzt(biaoZunExcelDTO.getFbzt());
            project.setSjzlbzml(biaoZunExcelDTO.getSjzlbzml());
            project.setCkwx(biaoZunExcelDTO.getCkwx());
            project.setSyfw(biaoZunExcelDTO.getSyfw());
            project.setSjzllx(biaoZunExcelDTO.getSjzllx());
            project.setCreateTime(LocalTimeUtils.getCurrentTime());
            project.setCreateUser("admin");
            project.setCreateUserFullName("admin(管理员)");
            project.setDescription(biaoZunExcelDTO.getCkwx());
            project.setName(biaoZunExcelDTO.getCnName());
            project.setProjectType(1);
            project.setModifyTime(LocalTimeUtils.getCurrentTime());
            projectRepository.save(project);
        }
        logger.info("存储数据库成功！");
    }
}
